import React, { useState, useEffect } from 'react';
import { Card, Input, Button, Upload, message, Space, Image } from 'antd';
import { PictureOutlined, SendOutlined, DeleteOutlined } from '@ant-design/icons';
import { publishTalk } from '@/services/Talk/api';
import { useUserId, useUserIdentity } from '@/hooks';
import type { UploadFile } from 'antd';
import styles from './index.less';

const { TextArea } = Input;

interface TalkPublishProps {
  onPublishSuccess?: () => void;
}

const TalkPublish: React.FC<TalkPublishProps> = ({ onPublishSuccess }) => {
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewImages, setPreviewImages] = useState<string[]>([]);
  const [canPublish, setCanPublish] = useState(true);
  
  // 获取当前用户ID（登录用户或匿名用户）
  const userId = useUserId();
  const identity = useUserIdentity();

  // 检查是否可以发布（匿名用户需要完善信息）
  useEffect(() => {
    const checkCanPublish = () => {
      if (identity.isLoggedIn) {
        // 已登录用户可以发布
        setCanPublish(true);
      } else {
        // 匿名用户需要检查是否已填写邮箱（name会自动生成）
        const localEmail = localStorage.getItem('anonymousUserEmail');
        setCanPublish(!!localEmail && !!localEmail.trim());
      }
    };

    // 初始检查
    checkCanPublish();

    // 监听storage事件（其他标签页或组件更新localStorage时触发）
    window.addEventListener('storage', checkCanPublish);
    
    // 定期检查（解决同一标签页内localStorage更新的问题）
    const intervalId = setInterval(checkCanPublish, 500);

    return () => {
      window.removeEventListener('storage', checkCanPublish);
      clearInterval(intervalId);
    };
  }, [identity.isLoggedIn]);

  // 处理图片上传
  const handleImageUpload = (file: File) => {
    // 检查文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      message.error(`图片大小不能超过5MB，当前文件大小：${(file.size / 1024 / 1024).toFixed(2)}MB`);
      return false;
    }

    // 检查文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      message.error('只支持上传 JPG、PNG、GIF、WebP 格式的图片');
      return false;
    }

    // 检查图片数量限制
    if (fileList.length >= 9) {
      message.error('最多只能上传9张图片');
      return false;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const imageUrl = e.target?.result as string;
      setPreviewImages(prev => [...prev, imageUrl]);
      setFileList(prev => [...prev, {
        uid: Date.now().toString(),
        name: file.name,
        status: 'done',
        url: imageUrl,
        originFileObj: file,
      } as UploadFile]);
    };
    reader.readAsDataURL(file);
    return false; // 阻止默认上传行为
  };

  // 删除图片
  const handleRemoveImage = (index: number) => {
    setPreviewImages(prev => prev.filter((_, i) => i !== index));
    setFileList(prev => prev.filter((_, i) => i !== index));
  };

  // 发布说说
  const handlePublish = async () => {
    // 检查是否可以发布
    if (!canPublish) {
      message.warning('请先完善您的邮箱信息才能发布说说');
      return;
    }

    if (!content.trim()) {
      message.warning('请输入说说内容');
      return;
    }

    // userId已通过useUserId hook获取（登录用户或临时用户）
    if (!userId) {
      message.error('用户ID获取失败，请刷新页面重试');
      return;
    }

    setLoading(true);
    try {
      // 创建FormData对象
      const formData = new FormData();
      formData.append('content', content.trim());
      formData.append('userId', userId.toString());
      
      // 添加图片文件
      fileList.forEach((file) => {
        if (file.originFileObj) {
          formData.append('images', file.originFileObj);
        }
      });
      
      await publishTalk(formData);
      
      message.success('发布成功！');
      setContent('');
      setPreviewImages([]);
      setFileList([]);
      onPublishSuccess?.();
    } catch (error) {
      message.error('发布失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card className={styles.publishCard}>
      <div className={styles.publishContainer}>
        <TextArea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder="分享你的想法..."
          autoSize={{ minRows: 3, maxRows: 8 }}
          className={styles.textArea}
          maxLength={500}
          showCount
        />
        
        {/* 图片预览区域 */}
        {previewImages.length > 0 && (
          <div className={styles.imagePreview}>
            <Space wrap>
              {previewImages.map((image, index) => (
                <div key={index} className={styles.imageItem}>
                  <Image
                    src={image}
                    alt={`预览图片${index + 1}`}
                    width={100}
                    height={100}
                    style={{ objectFit: 'cover', borderRadius: '8px' }}
                  />
                  <Button
                    type="text"
                    danger
                    size="small"
                    icon={<DeleteOutlined />}
                    className={styles.deleteBtn}
                    onClick={() => handleRemoveImage(index)}
                  />
                </div>
              ))}
            </Space>
          </div>
        )}
        
        <div className={styles.toolbar}>
          <Space>
            <Upload
              accept="image/*"
              showUploadList={false}
              beforeUpload={handleImageUpload}
              multiple
              disabled={!canPublish}
            >
              <Button 
                type="text" 
                icon={<PictureOutlined />}
                className={styles.toolBtn}
                disabled={!canPublish}
              >
                添加图片
              </Button>
            </Upload>
            {!canPublish && (
              <span className={styles.disabledTip}>
                请先完善个人信息
              </span>
            )}
          </Space>
          
          <Button
            type="primary"
            icon={<SendOutlined />}
            loading={loading}
            onClick={handlePublish}
            disabled={!content.trim() || !canPublish}
            className={styles.publishBtn}
            title={!canPublish ? '请先完善邮箱信息' : ''}
          >
            发布
          </Button>
        </div>
      </div>
    </Card>
  );
};

export default TalkPublish;